<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html>
<head>
<title>Arrays in C#</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="C#, arrays, tutorial, programming language, .NET, Mono, learn C#">
<meta name="description" content="In this part of the C# tutorial, we cover C# arrays.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>



<div class="content">

<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Arrays</h1>

<p>
In this part of the C# programming tutorial, we will cover arrays. 
We will initiate arrays and read data from them.
</p>

<p>
<b>Arrays</b> are collections of data. A variable can hold only one item at a time. 
Arrays can hold multiple items. These items are called elements of the array.
Arrays store data of the <b>same data type</b>. Each element can be referred
to by an index. Arrays are zero based. The index of the first element is zero.
Arrays are reference types. 
</p>

<p>
<b>Collections</b> serve the
similar purpose. They are are more powerful than arrays. They will be described later.
</p>

<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* NewSquare */
google_ad_slot = "0364418177";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script>

<p>
Arrays are used to store data of our applications.
We declare arrays to be of a certain data type. We specify their
length. And we initialize arrays with data. We have several
methods for working with arrays. We can modify the elements, sort
them, copy them or search them.
</p>

<h2>Initializing arrays</h2>

<p>
There are several ways, how we can initialize an array in C#. 
</p>


<pre class="code">
using System;

public class CSharpApp 
{
    static void Main() 
    {

        int[] array = new int[5];

        array[0] = 1;
        array[1] = 2;
        array[2] = 3;
        array[3] = 4;
        array[4] = 5;
        
        for (int i = 0; i &lt; array.Length; i++) 
        {
            Console.WriteLine(array[i]);
        }
        
      }
}
</pre>

<p>
We declare and initialize a numerical array. The contents of the
array are printed to the console. 
</p>

<pre class="explanation">
int[] array = new int[5];
</pre>

<p>
Here we declare an array which contains five elements. All elements
are integers. 
</p>

<pre class="explanation">
array[0] = 1;
array[1] = 2;
...
</pre>

<p>
We initialize the array with some data. This is assignment initialization. 
The indexes are in the square brackets. Number 3 is going to be
the first element of the array, 2 the second. 
</p>

<pre class="explanation">
for (int i = 0; i &lt; array.Length; i++) 
{
    Console.WriteLine(array[i]);
}
</pre>

<p>
We go through the array and print its elements. An array has a 
<code>Length</code> property, which gives the number of elements
in the array. Since arrays are zero based, the indexes are 0..length-1.
</p>

<hr class="btm">

<p>
We can declare and initialize an array in one statement.
</p>

<pre class="code">
using System;

public class CSharpApp 
{
    static void Main() 
    {
        int[] array = new int[] {2, 4, 5, 6, 7, 3, 2 };
        
        foreach (int i in array)
        {
            Console.WriteLine(i);
        }
      }
}
</pre>

<p>
This is a modified version of the previous program.
</p>

<pre class="explanation">
int[] array = new int[] {2, 4, 5, 6, 7, 3, 2 };
</pre>

<p>
An array is declared and initialized in one step. The elements
are specified in the curly brackets. We did not specify the length
of the array. The compiler will do it for us. 
</p>

<pre class="explanation">
foreach (int i in array)
{
    Console.WriteLine(i);
}
</pre>

<p>
We use the <code>foreach</code> keyword to traverse the array
and print its contents.
</p>



<h2>Array dimensions</h2>

<p>
So far, we have worked with one dimensional arrays. The number of indexes needed to 
specify an element is called the <b>dimension</b>, or <b>rank</b> of the array.
</p>

<p>
We will work with two dimensional array.
</p>

<pre class="code">
using System;

public class CSharpApp 
{
    static void Main() 
    {

        int[,] twodim = new int[,] { {1, 2, 3}, {1, 2, 3}  };

        int d1 = twodim.GetLength(0);
        int d2 = twodim.GetLength(1);

        for (int i=0; i&lt;d1; i++) 
        {
            for (int j=0; j&lt;d2; j++) 
            {
                Console.WriteLine(twodim[i, j]);
            } 
        }    
   }
}
</pre>

<p>
If we need two indexes to access an element in an array, than
we have a two dimensional array. 
</p>


<pre class="explanation">
int[,] twodim = new int[,] { {1, 2, 3}, {1, 2, 3}  };
</pre>

<p>
We declare and initialize a two dimensional array in one statement. 
Note the comma inside the square brackets.
</p>

<pre class="explanation">
int d1 = twodim.GetLength(0);
int d2 = twodim.GetLength(1);
</pre>

<p>
We get the dimensions of the array. The <code>GetLength()</code> gets
the number of elements in the specified dimension of the array.
</p>

<pre class="explanation">
for (int i=0; i&lt;d1; i++) 
{
    for (int j=0; j&lt;d2; j++) 
    {
        Console.WriteLine(twodim[i, j]);
    } 
}   
</pre>

<p>
We use two <code>for</code> loops to go through all the elements of a two 
dimensional array. Note that a specific array element is obtained
using two indexes, separated by a comma character. 
</p>

<pre>
$ ./twodim.exe 
1
2
3
1
2
3
</pre>

<p>
Output of the code example. 
</p>

<hr class="btm">

<p>
Next we will work with a three dimensional array.
</p>

<pre class="code">
using System;

public class CSharpApp 
{
    static void Main() 
    {

        int[,,] n3 = {
            {{12, 2, 8}},
            {{14, 5, 2}}, 
            {{3, 26, 9}},
            {{4, 11, 2}}
        };

        int d1 = n3.GetLength(0);
        int d2 = n3.GetLength(1);
        int d3 = n3.GetLength(2);

        for (int i=0; i&lt;d1; i++) 
        {
            for (int j=0; j&lt;d2; j++) 
            {
                for (int k=0; k&lt;d3; k++) 
                {
                    Console.Write(n3[i, j, k] + " ");
                } 
            } 
        }       
       Console.Write('\n');
   }
}
</pre>

<p>
We have a numerical three dimensional array. Again, we initialize
the array with numbers and print them to the terminal. 
</p>

<pre class="explanation">
int[,,] n3 = {
    {{12, 2, 8}},
    {{14, 5, 2}}, 
    {{3, 26, 9}},
    {{4, 11, 2}}
};
</pre>

<p>
There is another comma between the square brackets on the left side 
and additional curly brackets on the right side. 
</p>

<pre class="explanation">
for (int k=0; k&lt;d3; k++) 
{
    Console.Write(n3[i, j, k] + " ");
} 
</pre>

<p>
This loop goes through the third dimension. We use three indexes to
retrieve the value from the array. 
</p>

<pre>
$ ./threedim.exe 
12 2 8 14 5 2 3 26 9 4 11 2
</pre>

<p>
We print the contents of the three dimensional array to the
console. 
</p>

<hr class="btm">

<p>
There is a <code>Rank</code> property, which gives
the number of dimensions of an array.
</p>

<pre class="code">
using System;

public class CSharpApp 
{
    static void Main() 
    {

        int[]   a1 = {1, 2};
        int[,]  a2 = { { 1 }, { 2 } };
        int[,,] a3 = { { { 1, 2 }, { 2, 1 } } };

        Console.WriteLine(a1.Rank);
        Console.WriteLine(a2.Rank);
        Console.WriteLine(a3.Rank);
   }
}
</pre>

<p>
We have three arrays. We use the <code>Rank</code> property
to get the number of dimensions for each of them. 
</p>

<pre class="explanation">
Console.WriteLine(a1.Rank);
</pre>

<p>
Here we get the rank for the first array.
</p>

<pre>
$ ./rank.exe 
1
2
3
</pre>

<p>
Output of the program.
</p>

<h2>Jagged arrays</h2>

<p>
Arrays that have elements of the same size are called <b>rectangular</b> arrays.
In contrast, arrays which have elements of different size are called 
<b>jagged</b> arrays. Jagged arrays are declared and initialized differently.
</p>

<pre class="code">
using System;

public class CSharpApp {

    static void Main() 
    {
               
        int[][] jagged = new int[][] 
        {
            new int[] { 1, 2 },
            new int[] { 1, 2, 3 },
            new int[] { 1, 2, 3, 4 }
        };

        foreach (int[] array in jagged) {
            foreach (int e in array) {
                Console.Write(e + " ");
            }
        }
        Console.Write('\n');
    }
}
</pre>

<p>
This is an example of a jagged array. 
</p>

<pre class="explanation">
int[][] jagged = new int[][] 
{
    new int[] { 1, 2 },
    new int[] { 1, 2, 3 },
    new int[] { 1, 2, 3, 4 }
};
</pre>

<p>
This is a declaration and initialization of a jagged array. 
Note that this time, we use two pairs of square brackets.
We have an array of arrays. More specifically, we have 
declared an array to have three arrays of int data type. 
Each of the arrays has different number of elements. 
</p>

<pre class="explanation">
foreach (int[] array in jagged) {
    foreach (int e in array) {
        Console.Write(e + " ");
    }
}
</pre>

<p>
We use two foreach loops to traverse the jagged array. 
In the first loop, we get the array. In the second loop,
we get the elements of the obtained array.
</p>

<h2>Array methods</h2>

<p>
There are various methods for working with arrays. 
These methods can be used for retrieving, modifying,
sorting, copying, searching data. These methods that
we use are static methods of the Array class or member methods
of the array objects. 
</p>

<pre class="code">
using System;

public class CSharpApp {

    static void Main() 
    {
               
        string[] names = {"Jane", "Frank", "Alice", "Tom" };

        Array.Sort(names);

        foreach(string el in names)
        {
            Console.Write(el + " ");
        }

        Console.Write('\n');

        Array.Reverse(names);

        foreach(string el in names)
        {
            Console.Write(el + " ");
        }

        Console.Write('\n');
    }
}
</pre>

<p>
In this example, we sort the data. 
</p>

<pre class="explanation">
string[] names = {"Jane", "Frank", "Alice", "Tom" };
</pre>

<p>
We have an array of strings. 
</p>

<pre class="explanation">
Array.Sort(names);
</pre>

<p>
The static <code>Sort()</code> method sorts the data alphabetically.
</p>

<pre class="explanation">
Array.Reverse(names);
</pre>

<p>
The <code>Reverse()</code> method reverses the sequence of 
the elements in the entire one-dimensional array.
</p>

<pre>
$ ./sorting.exe 
Alice Frank Jane Tom 
Tom Jane Frank Alice
</pre>

<p>
We have ordered the names in ascending and descending order. 
</p>

<hr class="btm">

<p>
The following example uses <code>SeValue()</code>,
<code>GetValue()</code>, <code>IndexOf()</code>, 
<code>Copy()</code> and <code>Clear()</code> methods.
</p>

<pre class="code">
using System;

public class CSharpApp {

    static void Main() 
    {           
        string[] names = {"Jane", "Frank", "Alice", "Tom"};
        string[] girls = new string[5];

        names.SetValue("Beky", 1);
        names.SetValue("Erzebeth", 3);

        Console.WriteLine(names.GetValue(1));
        Console.WriteLine(names.GetValue(3));

        Console.WriteLine(Array.IndexOf(names, "Erzebeth"));

        Array.Copy(names, girls, names.Length);

        foreach(string girl in girls)
        {
            Console.Write(girl + " ");
        }
       
        Console.Write('\n');

        Array.Clear(names, 0, 2);

        foreach(string name in names)
        {
            Console.Write(name + " ");
        }

        Console.Write('\n');
    }
}
</pre>

<p>
This example introduces additional methods. 
</p>


<pre class="explanation">
names.SetValue("Beky", 1);
names.SetValue("Erzebeth", 3);
</pre>

<p>
The <code>SetValue()</code> sets a value for a 
specific index in the array. 
</p>

<pre class="explanation">
Console.WriteLine(names.GetValue(1));
Console.WriteLine(names.GetValue(3));
</pre>

<p>
We retrieve the values from the array with the 
<code>GetValue()</code> method.
</p>

<pre class="explanation">
Console.WriteLine(Array.IndexOf(names, "Erzebeth"));
</pre>

<p>
The <code>IndexOf()</code> method returns an index
for the first occurrence of a specific value. 
</p>

<pre class="explanation">
Array.Copy(names, girls, names.Length);
</pre>

<p>
The <code>Copy()</code> method copies values
from the source array to the destination array. The first parameter
is the source array, the second is the destination array. The third
parameter is the length; it specifies the number of elements to copy.
</p>

<pre class="explanation">
Array.Clear(names, 0, 2);
</pre>

<p>
The <code>Clear()</code> method clears elements from the array.
It takes three parameters, the array, the start index and the number 
of elements from the index to clear.
</p>

<pre>
$ ./arraymethods.exe 
Beky
Erzebeth
3
Jane Beky Alice Erzebeth  
  Alice Erzebeth 
</pre>

<p>
Output.
</p>

<p>
In this part of the C# tutorial, we worked with arrays. 
We described various types of arrays and methods to work with them.
</p>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified October 16, 2010  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

